import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import os
import shutil
from pathlib import Path
import threading

class FileFilterApp:
    def __init__(self, root):
        self.root = root
        self.root.title("文件筛选工具")
        self.root.geometry("600x400")
        self.root.resizable(True, True)
        
        # 设置窗口图标和样式
        self.setup_styles()
        
        # 创建主框架
        self.main_frame = ttk.Frame(root, padding="10")
        self.main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 配置网格权重
        root.columnconfigure(0, weight=1)
        root.rowconfigure(0, weight=1)
        self.main_frame.columnconfigure(1, weight=1)
        
        # 存储路径变量
        self.folder_a_path = tk.StringVar()
        self.folder_b_path = tk.StringVar()
        self.folder_c_path = tk.StringVar()
        
        # 创建界面元素
        self.create_widgets()
        
    def setup_styles(self):
        """设置界面样式"""
        style = ttk.Style()
        style.theme_use('clam')
        
    def create_widgets(self):
        """创建界面组件"""
        # 标题
        title_label = ttk.Label(self.main_frame, text="文件筛选工具", 
                               font=("微软雅黑", 16, "bold"))
        title_label.grid(row=0, column=0, columnspan=3, pady=(0, 20))
        
        # 功能说明
        desc_frame = ttk.LabelFrame(self.main_frame, text="功能说明", padding="10")
        desc_frame.grid(row=1, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=(0, 20))
        
        desc_text = ("功能：将A文件夹中与B文件夹内命名相同的文件保存到C文件夹\n"
                    "A文件夹为待筛选文件夹，B文件夹为目标文件夹，C文件夹为已筛选文件夹")
        desc_label = ttk.Label(desc_frame, text=desc_text, font=("微软雅黑", 10))
        desc_label.pack()
        
        # A文件夹选择
        ttk.Label(self.main_frame, text="A文件夹（待筛选文件夹）:", 
                 font=("微软雅黑", 10)).grid(row=2, column=0, sticky=tk.W, pady=5)
        self.folder_a_entry = ttk.Entry(self.main_frame, textvariable=self.folder_a_path, 
                                       width=50, font=("微软雅黑", 9))
        self.folder_a_entry.grid(row=2, column=1, sticky=(tk.W, tk.E), padx=(10, 5), pady=5)
        ttk.Button(self.main_frame, text="浏览", command=self.browse_folder_a,
                  width=10).grid(row=2, column=2, padx=(5, 0), pady=5)
        
        # B文件夹选择
        ttk.Label(self.main_frame, text="B文件夹（目标文件夹）:", 
                 font=("微软雅黑", 10)).grid(row=3, column=0, sticky=tk.W, pady=5)
        self.folder_b_entry = ttk.Entry(self.main_frame, textvariable=self.folder_b_path, 
                                       width=50, font=("微软雅黑", 9))
        self.folder_b_entry.grid(row=3, column=1, sticky=(tk.W, tk.E), padx=(10, 5), pady=5)
        ttk.Button(self.main_frame, text="浏览", command=self.browse_folder_b,
                  width=10).grid(row=3, column=2, padx=(5, 0), pady=5)
        
        # C文件夹选择
        ttk.Label(self.main_frame, text="C文件夹（已筛选文件夹）:", 
                 font=("微软雅黑", 10)).grid(row=4, column=0, sticky=tk.W, pady=5)
        self.folder_c_entry = ttk.Entry(self.main_frame, textvariable=self.folder_c_path, 
                                       width=50, font=("微软雅黑", 9))
        self.folder_c_entry.grid(row=4, column=1, sticky=(tk.W, tk.E), padx=(10, 5), pady=5)
        ttk.Button(self.main_frame, text="浏览", command=self.browse_folder_c,
                  width=10).grid(row=4, column=2, padx=(5, 0), pady=5)
        
        # 操作按钮
        button_frame = ttk.Frame(self.main_frame)
        button_frame.grid(row=5, column=0, columnspan=3, pady=20)
        
        self.start_button = ttk.Button(button_frame, text="开始筛选", 
                                      command=self.start_filtering, width=15)
        self.start_button.pack(side=tk.LEFT, padx=5)
        
        ttk.Button(button_frame, text="清空路径", command=self.clear_paths, 
                  width=15).pack(side=tk.LEFT, padx=5)
        
        # 进度条
        self.progress = ttk.Progressbar(self.main_frame, mode='indeterminate')
        self.progress.grid(row=6, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=10)
        
        # 状态标签
        self.status_label = ttk.Label(self.main_frame, text="请选择文件夹路径", 
                                     font=("微软雅黑", 9))
        self.status_label.grid(row=7, column=0, columnspan=3, pady=5)
        
    def browse_folder_a(self):
        """浏览A文件夹"""
        folder = filedialog.askdirectory(title="选择A文件夹（待筛选文件夹）")
        if folder:
            self.folder_a_path.set(folder)
            
    def browse_folder_b(self):
        """浏览B文件夹"""
        folder = filedialog.askdirectory(title="选择B文件夹（目标文件夹）")
        if folder:
            self.folder_b_path.set(folder)
            
    def browse_folder_c(self):
        """浏览C文件夹"""
        folder = filedialog.askdirectory(title="选择C文件夹（已筛选文件夹）")
        if folder:
            self.folder_c_path.set(folder)
            
    def clear_paths(self):
        """清空所有路径"""
        self.folder_a_path.set("")
        self.folder_b_path.set("")
        self.folder_c_path.set("")
        self.status_label.config(text="请选择文件夹路径")
        
    def validate_paths(self):
        """验证路径是否有效"""
        if not self.folder_a_path.get():
            messagebox.showerror("错误", "请选择A文件夹路径")
            return False
        if not self.folder_b_path.get():
            messagebox.showerror("错误", "请选择B文件夹路径")
            return False
        if not self.folder_c_path.get():
            messagebox.showerror("错误", "请选择C文件夹路径")
            return False
            
        if not os.path.exists(self.folder_a_path.get()):
            messagebox.showerror("错误", "A文件夹不存在")
            return False
        if not os.path.exists(self.folder_b_path.get()):
            messagebox.showerror("错误", "B文件夹不存在")
            return False
            
        return True
        
    def get_filename_without_extension(self, filepath):
        """获取不带扩展名的文件名"""
        return Path(filepath).stem
        
    def start_filtering(self):
        """开始筛选文件"""
        if not self.validate_paths():
            return
            
        # 禁用开始按钮，启动进度条
        self.start_button.config(state='disabled')
        self.progress.start()
        self.status_label.config(text="正在筛选文件...")
        
        # 在新线程中执行筛选操作
        thread = threading.Thread(target=self.filter_files)
        thread.daemon = True
        thread.start()
        
    def filter_files(self):
        """执行文件筛选"""
        try:
            folder_a = self.folder_a_path.get()
            folder_b = self.folder_b_path.get()
            folder_c = self.folder_c_path.get()
            
            # 确保C文件夹存在
            os.makedirs(folder_c, exist_ok=True)
            
            # 获取B文件夹中所有文件的名称（不含扩展名）
            b_files = set()
            for root, dirs, files in os.walk(folder_b):
                for file in files:
                    filename_without_ext = self.get_filename_without_extension(file)
                    b_files.add(filename_without_ext)
            
            # 筛选A文件夹中的文件
            copied_count = 0
            for root, dirs, files in os.walk(folder_a):
                for file in files:
                    filename_without_ext = self.get_filename_without_extension(file)
                    if filename_without_ext in b_files:
                        # 找到匹配的文件，复制到C文件夹
                        source_path = os.path.join(root, file)
                        dest_path = os.path.join(folder_c, file)
                        
                        # 如果目标文件已存在，添加数字后缀
                        counter = 1
                        original_dest_path = dest_path
                        while os.path.exists(dest_path):
                            name, ext = os.path.splitext(original_dest_path)
                            dest_path = f"{name}_{counter}{ext}"
                            counter += 1
                            
                        shutil.copy2(source_path, dest_path)
                        copied_count += 1
            
            # 在主线程中更新UI
            self.root.after(0, self.filtering_completed, copied_count)
            
        except Exception as e:
            # 在主线程中显示错误
            self.root.after(0, self.show_error, str(e))
            
    def filtering_completed(self, copied_count):
        """筛选完成后的处理"""
        self.progress.stop()
        self.start_button.config(state='normal')
        self.status_label.config(text=f"筛选完成！共复制了 {copied_count} 个文件到C文件夹")
        messagebox.showinfo("完成", f"文件筛选完成！\n共复制了 {copied_count} 个文件到C文件夹")
        
    def show_error(self, error_message):
        """显示错误信息"""
        self.progress.stop()
        self.start_button.config(state='normal')
        self.status_label.config(text="筛选过程中出现错误")
        messagebox.showerror("错误", f"筛选过程中出现错误：\n{error_message}")

def main():
    """主函数"""
    root = tk.Tk()
    app = FileFilterApp(root)
    root.mainloop()

if __name__ == "__main__":
    main() 